package service

import (
	"bytes"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"path/filepath"
	"time"
	"zhuandan/tool"
	"zhuandan/utils"
)

func Upload(fileName string, fileByte []byte) (url string, err error) {

	/*
	   oss 的相关配置信息
	*/
	config := tool.GetConfig().Oss
	bucketName := config.Bucket
	endpoint := config.Endpoint
	accessKeyId := config.AccessKeyId
	accessKeySecret := config.AccessKeySecret
	domain := config.Domain
	//创建OSSClient实例
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		return url, err
	}

	// 获取存储空间
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return url, err
	}

	//上传阿里云路径
	folderName := time.Now().Format("2006-01-02")
	yunFileTmpPath := filepath.Join("zhuandan") + "/" + folderName + "/" + utils.Int64string(time.Now().Unix()) + fileName //uploads/2020-06-17/GoLang (1).docx

	// 上传Byte数组
	err = bucket.PutObject(yunFileTmpPath, bytes.NewReader([]byte(fileByte)))
	if err != nil {
		return url, err
	}

	return domain + "/" + yunFileTmpPath, nil
}
